package com.trkj.service.wdm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.wdm.EmpPassDAO;
import com.trkj.dao.wdm.StaffInformationDAO;
import com.trkj.mybatisdao.staffDeptDAO;
import com.trkj.pojo.Emppass;
import com.trkj.pojo.Function;
import com.trkj.pojo.Role;
import com.trkj.pojo.StaffInformation;
import com.trkj.service.ServiceException;

@Service
@Transactional(rollbackFor=Exception.class)
public class EmpPassService {
	public static final Long LOGIN_ID = 1l;
	@Autowired
	private EmpPassDAO emppass;
	@Autowired
	private StaffInformationDAO staffinformation;
	@Autowired
	private staffDeptDAO staffdeptDAO;
	
	/**
	 * 保存用户
	 * @param name
	 * @return
	 * @throws ServiceException
	 */
	public StaffInformation user(String name) throws ServiceException{
		try {
			return staffinformation.queryName(name);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	
	
	
	/**
	 * 登录验证判断
	 * @param name
	 * @param pwd
	 * @return
	 * @throws ServiceException
	 */
	public boolean LoginVerify(String name,String pwd)throws ServiceException{
		try {
			StaffInformation s =staffinformation.queryName(name);
			if(s!=null){
				Long e1 =staffdeptDAO.findPaddId(s.getStainId());
				Set<Long> set = findAllFunction(e1);
				if(s!=null&&set.contains(LOGIN_ID)){ 
					String es =staffdeptDAO.findPassPwd(s.getStainId());
					if(pwd.equals(es)){
						return true;
					}
				}
			}
				return false;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}
	public Long select(String name){
		StaffInformation s =staffinformation.queryName(name);
			Long e =staffdeptDAO.findPaddId(s.getStainId());
			return e;
		
	}
	/**
	 * 查询用户的所有权限
	 * @param passId
	 * @return
	 */
	public Set<Long> findAllFunction(Long passId){
			//set集合中不可以有重复的值
			Set<Long> funId = new HashSet<>();
			Emppass emps = emppass.findOne(passId);
			List<Role> rs =emps.getRoles();
			
			if(rs!=null){
				for (Role role2 : rs) {
					List<Function> fun = role2.getFunctions();
					if(fun!=null){
						for (Function function : fun) {
							funId.add(function.getFunId());
						}
					}
				}
			}
			return funId;
		
	}
	

}
